package cn.tom.tool;

import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;

public class DateTool {
    //日期格式转换
    @InitBinder
    public void initBinder(final WebDataBinder webdataBinder) {
        webdataBinder.registerCustomEditor(java.util.Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                System.out.println("text==" + text);
                if (text == null || text.length() < 6) {
                    setValue(null);
                }
                if (text.indexOf("-") > 0) { // yyyy-MM-dd HH:mm:ss                     
                    if (text.indexOf(":") < 1) {
                        text = text + " 00:00:00";
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        java.util.Date d = sdf.parse(text);
                        setValue(d);
                    } catch (Exception e) {
                        System.out.println("书本日期错误...." + text);
                        setValue(new java.util.Date());  //毫秒                  
                    }
                } else {
                    setValue(new java.util.Date(Long.valueOf(text)));
                } //毫秒时间戳              
            }
        });
    }
}
